package com.xmy.cultivate.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.constants.CommonConstant;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.GradePositionRequest;
import com.xmy.cultivate.entity.views.SchedulingClash;
import com.xmy.cultivate.entity.views.SelectStudent;
import com.xmy.cultivate.enums.SourseLeveEnum;
import com.xmy.cultivate.enums.StatusGradeEnum;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/grade")
@Scope("prototype")
public class GradeController extends BaseController {

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IDictService iDictService;

    @Autowired
    @Lazy
    ICourseSchedulingAlwaysService iCourseSchedulingAlwaysService;

    @Autowired
    @Lazy
    IStudentClassTypeService iStudentClassTypeService;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    @Lazy
    IStudentService studentService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;

    @Autowired
    @Lazy
    ICisPositionService iCisPositionService;

    @Autowired
    @Lazy
    IGradeLayerService iGradeLayerService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    @Autowired
    ICourseTypeService iCourseTypeService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IRoleAdminService iRoleAdminService;

    @Autowired
    IFinanceService iFinanceService;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @GetMapping()
    public Result findAll(@RequestParam Map<String, String> reMap,
                          @RequestParam(value = "keyType", defaultValue = "1") String keyType,
                          @RequestParam(value = "schoolIdList", defaultValue = "") String schoolId,
                          @RequestParam(value = "classTypeIdStr", defaultValue = "") String classTypeIdStr,
                          @RequestParam(value = "classRoomIdList", defaultValue = "") String classRoomId,
                          @RequestParam(value = "courseIdList", defaultValue = "") String courseId,
                          @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                          @RequestParam(value = "quarterNumList", defaultValue = "") String quarterNum,
                          @RequestParam(value = "yearClassIdList", defaultValue = "") String yearClassIdList,
                          @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
                          @RequestParam(value = "isCheckHouse", defaultValue = "") String isCheckHouse,
                          @RequestParam(value = "lessonType", defaultValue = "1") String lessonType,
                          @RequestParam(value = "isRebrush", defaultValue = "") String isRebrush
    ) {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize"));

        Page<Grade> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        String name = reMap.get("name");//名称
        //String course_type_id =  reMap.get("course_type_id");
        String subjectsId = reMap.get("subjectsId");
        String status = reMap.get("status");

        String teacherId = reMap.get("teacherId");

        if (StringUtils.isBlank(yearPart)) {
            yearPart = quarterNow.getYearPart().toString();
        }
        if (StringUtils.isBlank(quarterNum)) {
            quarterNum = quarterNow.getNum().toString();
        }

        //String yearClassId = reMap.get("yearClassId");

        /**
         * 是否排课
         */
        String isScheduling = reMap.get("isScheduling");


        if (StringUtils.isBlank(schoolId)) {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }
        if (StringUtils.isNotBlank(keyType)) {
            if (keyType == "3") {
                //课程
                queryWrapper.inSql(StringUtils.isNotBlank(name), "course_id", "select * from course where name like '%" + name + "%' ");
            } else if (keyType == "2") {
                //班主任
                queryWrapper.inSql(StringUtils.isNotBlank(name), "teacher_id", "select * from staff where name like '%" + name + "%' ");
            } else {
                queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
            }
        }

        if (StringUtils.isNotBlank(isScheduling)) {
            if (isScheduling.equals("1")) {
                queryWrapper.inSql("id", "select grade_id from course_scheduling_detail where deleted=0 GROUP BY grade_id");
            } else {
                queryWrapper.notInSql("id", "select grade_id from course_scheduling_detail where deleted=0 GROUP BY grade_id");
            }
        }

        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.inSql(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        queryWrapper.eq(StringUtils.isNotBlank(classRoomId), "class_room_id", classRoomId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(isRebrush), "is_rebrush", isRebrush);

        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);

        queryWrapper.inSql(StringUtils.isNotBlank(classTypeIdStr), "course_type_id", classTypeIdStr);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq("status", status);
        }
        if (StringUtils.isNotBlank(yearClassId)) {
            yearClassIdList = yearClassId;
        }
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassIdList), "year_class_id", yearClassIdList);
        if (StringUtils.isNotBlank(isCheckHouse)) {
            if (isCheckHouse.equals("0")) {
                queryWrapper.inSql("id", "select grade_id from student_grade where `quarter_num`=" + quarterNum + " and year_part = " + yearPart + " and status<>3 and is_check_house = 0 and deleted=0 GROUP BY grade_id");
            } else {
                queryWrapper.notInSql("id", "select grade_id from student_grade where `quarter_num`=" + quarterNum + " and year_part = " + yearPart + " and status<>3 and is_check_house = 0 and deleted=0 GROUP BY grade_id");
                queryWrapper.inSql("id", "select grade_id from student_grade where `quarter_num`=" + quarterNum + " and year_part = " + yearPart + " and status<>3 and deleted=0 GROUP BY grade_id");
            }
        }

        if (this.sourseLeveEnum.equals(SourseLeveEnum.ONESELF)) {
            queryWrapper.eq("teacher_id", this.adminId);
        }

        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("created_at");

        IPage<Grade> iPage = iGradeService.findAll(page, queryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("/getStatistics")
    public Result getStatistics(@RequestParam Map<String, String> reMap,
                                @RequestParam(value = "keyType", defaultValue = "1") String keyType,
                                @RequestParam(value = "schoolIdList", defaultValue = "") String schoolId,
                                @RequestParam(value = "courseTypeIdList", defaultValue = "") String courseTypeId,
                                @RequestParam(value = "classRoomIdList", defaultValue = "") String classRoomId,
                                @RequestParam(value = "courseIdList", defaultValue = "") String courseId,
                                @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                                @RequestParam(value = "quarterNumList", defaultValue = "") String quarterNum,
                                @RequestParam(value = "yearClassIdList", defaultValue = "") String yearClassId,
                                @RequestParam(value = "lessonType", defaultValue = "1") String lessonType) {

        Quarter quarterNow = iQuarterService.getNowQuarter();
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        String name = reMap.get("name");//名称
        //String course_type_id =  reMap.get("course_type_id");
        String subjectsId = reMap.get("subjectsId");
        String status = reMap.get("status");

        String teacherId = reMap.get("teacherId");

        if (StringUtils.isBlank(yearPart)) {
            yearPart = quarterNow.getYearPart().toString();
        }
        if (StringUtils.isBlank(quarterNum)) {
            quarterNum = quarterNow.getNum().toString();
        }

        /**
         * 是否排课
         */
        String isScheduling = reMap.get("isScheduling");


        if (StringUtils.isBlank(schoolId)) {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }
        if (StringUtils.isNotBlank(keyType)) {
            if (keyType == "3") {
                //课程
                queryWrapper.inSql(StringUtils.isNotBlank(name), "course_id", "select * from course where name like '%" + name + "%' ");
            } else if (keyType == "2") {
                //班主任
                queryWrapper.inSql(StringUtils.isNotBlank(name), "teacher_id", "select * from staff where name like '%" + name + "%' ");
            } else {
                queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
            }
        }

        if (StringUtils.isNotBlank(isScheduling)) {
            if (isScheduling.equals("1")) {
                queryWrapper.inSql("id", "select grade_id from course_scheduling where deleted=0 GROUP BY grade_id");
            } else {
                queryWrapper.notInSql("id", "select grade_id from course_scheduling where deleted=0 GROUP BY grade_id");
            }
        }

        //Long openGradeCount = iGradeService.count(new QueryWrapper<Grade>().eq("year_part",yearPart).eq("quarter_num",quarterNum).eq("status",1));

        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.inSql(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        //queryWrapper.eq(StringUtils.isNotBlank(classRoomId),"class_room_id",classRoomId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("created_at");
        queryWrapper.eq("status", 1);

        if (this.sourseLeveEnum.equals(SourseLeveEnum.ONESELF)) {
            queryWrapper.eq("teacher_id", this.adminId);
        }

        //获取出班级
        List<Long> gradeIdList = iGradeService.findGradeIdList(queryWrapper);
        //where grade_id =1 and deleted = 0 and `status` = 1 and reading_status = 1

        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("deleted", 0);
        studentGradeQueryWrapper.eq("status", 1);
        studentGradeQueryWrapper.eq(yearPart != null, "year_part", yearPart);
        studentGradeQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        if (gradeIdList.size() > 0) {
            studentGradeQueryWrapper.in("grade_id", gradeIdList);
        } else {
            //没有就用0替代
            studentGradeQueryWrapper.eq("grade_id", 0);
        }
        studentGradeQueryWrapper.groupBy("school_id", "student_id", "subjects_id");
        studentGradeQueryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        QueryWrapper<StudentGrade> studentGradeQueryAdvanceWrapper = studentGradeQueryWrapper.clone();//预分班人数
        studentGradeQueryWrapper.eq("reading_status", 1);
//        Long count = iStudentGradeService.getStudentCount(studentGradeQueryWrapper);
        //预分班人数
        studentGradeQueryAdvanceWrapper.eq("reading_status", 0);
        Long advanceCount = iStudentGradeService.getStudentCount(studentGradeQueryAdvanceWrapper);

        // 在校学员
        QueryWrapper<StudentGrade> studentGradeQueryManTimeWrapper = new QueryWrapper<>();
        studentGradeQueryManTimeWrapper.eq("deleted", 0);
        studentGradeQueryManTimeWrapper.eq("status", 1);
        studentGradeQueryManTimeWrapper.eq(yearPart != null, "year_part", yearPart);
        studentGradeQueryManTimeWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        if (gradeIdList.size() > 0) {
            studentGradeQueryManTimeWrapper.in("grade_id", gradeIdList);
        } else {
            //没有就用0替代
            studentGradeQueryManTimeWrapper.eq("grade_id", 0);
        }
        studentGradeQueryManTimeWrapper.groupBy("school_id", "student_id", "subjects_id");
        studentGradeQueryManTimeWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
//        if (lessonType.equals("1")) {
        studentGradeQueryManTimeWrapper.ge("student_grade.use_course_count", 1);
//        }

        Long manTimeCount = iStudentGradeService.getStudentCount(studentGradeQueryManTimeWrapper);

        //已核对学生人数
        queryWrapper.eq("is_check_house", 1);


        /**
         * 应核对总人数
         */
        Long studentCheckCountAll = iStudentGradeService.getStudentCheckCount(yearPart, quarterNum, schoolId, subjectsId, yearClassId, courseId, teacherId, null, lessonType, this.sourseLeve, this.adminId);

        //未核对学生人数
        Long studentNnconfirmedCount = iStudentGradeService.getStudentCheckCount(yearPart, quarterNum, schoolId, subjectsId, yearClassId, courseId, teacherId, "0", lessonType, this.sourseLeve, this.adminId);

        //在读学员（和财务报表一致）
        Integer count = studentGradeMapper.readingStudentCount(yearPart, quarterNum, schoolId, subjectsId, lessonType, yearClassId, teacherId, status, isScheduling, this.sourseLeve, this.adminId);

        Map<String, Object> map = new HashMap<>();
        map.put("studentCount", count);
        map.put("advanceCount", advanceCount);//预分班人数
        map.put("studemanTimeCountntCount", manTimeCount);// 在校学员
        map.put("studentAbnormalCount", 10);
        //已核对
        map.put("studentVerifyCount", studentCheckCountAll - studentNnconfirmedCount);
        //未核对
        map.put("studentNnconfirmedCount", studentNnconfirmedCount);
        return new Result(Code.OK, map, "成功");
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") Long id) {
        Grade grade = iGradeService.getOneForId(id);

        //StatusEnum statusEnum = grade.getStatus();
        //System.out.print("statusEnum:"+statusEnum.getStatus());
        return new Result(Code.OK, grade);
    }


    @PostMapping()
    @RepeatSubmit(expireSeconds = 30)
    public Result save(@RequestBody Grade grade) throws ParseException {

        if (grade.getIsAutoScheduling() == null) {
            grade.setIsAutoScheduling(1);
        }

        Course course = iCourseService.getById(grade.getCourseId());
        Integer i = 0;
        Long teacherId = null;
        for (TypeValueData typeValueData : grade.getTeacherList()) {
            if (typeValueData.getValueId() != null && typeValueData.getTypeId() != null) {
                if (typeValueData.getTypeId() == 1) {
                    if (i == 0) {
                        teacherId = typeValueData.getValueId();
                    }
                }
                i++;
            }
        }

        if (teacherId != null && grade.getIsMakeup().equals(0) && grade.getIsAutoScheduling().equals(1)) {
            //grade.setStatus(StatusEnum.DISABLE);
            QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
            //gradeQueryWrapper.eq("school_id",grade.getSchoolId());
            gradeQueryWrapper.eq("lesson_type", 1);
            gradeQueryWrapper.eq("year_part", grade.getYearPart());
            gradeQueryWrapper.eq("quarter_num", course.getQuarterNum());
            gradeQueryWrapper.eq("teacher_id", teacherId);
            gradeQueryWrapper.eq("week_dates", grade.getWeekDates());
            gradeQueryWrapper.eq("time_start", grade.getTimeStart().trim());
            gradeQueryWrapper.eq("time_end", grade.getTimeEnd().trim());
            List<Grade> gradeList = iGradeService.list(gradeQueryWrapper);
            if (course.getLessonType().equals(1)) {
                if (gradeList.size() > 0) {
                    StringBuilder stringBuilder = new StringBuilder();
                    Long count = 0L;
                    for (Grade gradeItem : gradeList) {
                        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
                        courseSchedulingDetailQueryWrapper.eq("grade_id", gradeItem.getId());
                        courseSchedulingDetailQueryWrapper.eq("lesson_type", 1);
                        courseSchedulingDetailQueryWrapper.eq("status", 0);
                        Long schedulingCount = iCourseSchedulingDetailService.count(courseSchedulingDetailQueryWrapper);
                        if (schedulingCount > 0) {
                            count = count + schedulingCount;
                            stringBuilder.append(gradeItem.getName()).append(",");
                        }
                    }
                    //允许时间冲突
                    if (grade.getAllowTimeClash() != null && !grade.getAllowTimeClash().equals(1)) {
                        if (count > 0) {
                            return new Result(Code.ERROR, "", "该时间段老师已经有排课，" + stringBuilder.toString() + "不能重复排课");
                        }
                    }
                }
            }

            gradeQueryWrapper.clear();
            gradeQueryWrapper.eq("school_id", grade.getSchoolId());
            gradeQueryWrapper.eq("year_part", grade.getYearPart());
            gradeQueryWrapper.eq("quarter_num", course.getQuarterNum());
            gradeQueryWrapper.eq("class_room_id", grade.getClassRoomId());
            gradeQueryWrapper.eq("week_dates", grade.getWeekDates());
            gradeQueryWrapper.eq("time_start", grade.getTimeStart().trim());
            gradeQueryWrapper.eq("time_end", grade.getTimeEnd().trim());
            Long count = iGradeService.count(gradeQueryWrapper);
            if (course.getLessonType().equals(1)) {
                if (grade.getAllowTimeClash() != null && !grade.getAllowTimeClash().equals(1)) {
                    if (count > 0) {
                        return new Result(Code.ERROR, "", "该时间段教室已经有排课，不能重复排课");
                    }
                }
            }
        }
        grade.setSubjectsId(course.getSubjectsId());
        grade.setLessonType(course.getLessonType());
        Integer schedulintCount = iGradeService.saveTo(grade);
        if (grade.getIsMakeup().equals(0) && grade.getIsAutoScheduling().equals(1)) {
            //schedulintCount = iCourseSchedulingService.autoScheduling(grade.getId(), null);
            iMqPushService.autoScheduling(grade.getId(), null);
        }
        return new Result(Code.OK, "", "保存成功");
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id, @RequestBody Grade grade) throws ParseException {

        Grade gradeOld = iGradeService.getById(grade.getId());
        if (grade.getIsMakeup() != gradeOld.getIsMakeup()) {
            if (gradeOld.getIsMakeup().equals(0)) {
                return new Result(Code.ERROR, "", "不能改为补课班");
            } else {
                return new Result(Code.ERROR, "", "不能改为非补课班");
            }
        }

        if (grade.getIsAutoScheduling() == null) {
            grade.setIsAutoScheduling(1);
        }


        Course course = iCourseService.getById(grade.getCourseId());
        Integer i = 0;
        Long teacherId = null;
        for (TypeValueData typeValueData : grade.getTeacherList()) {
            if (typeValueData.getValueId() != null && typeValueData.getTypeId() != null) {
                if (typeValueData.getTypeId() == 1) {
                    if (i == 0) {
                        teacherId = typeValueData.getValueId();
                    }
                }
                i++;
            }
        }


        QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
        //gradeQueryWrapper.eq("school_id",grade.getSchoolId());
        gradeQueryWrapper.ne("id", grade.getId());
        gradeQueryWrapper.eq("lesson_type", 1);
        gradeQueryWrapper.eq("year_part", grade.getYearPart());
        gradeQueryWrapper.eq("quarter_num", course.getQuarterNum());
        gradeQueryWrapper.eq("teacher_id", teacherId);
        gradeQueryWrapper.eq("week_dates", grade.getWeekDates());
        gradeQueryWrapper.eq("time_start", grade.getTimeStart().trim());
        gradeQueryWrapper.eq("time_end", grade.getTimeEnd().trim());
        List<Grade> gradeList = iGradeService.list(gradeQueryWrapper);
        if (course.getLessonType().equals(1) && grade.getIsAutoScheduling().equals(1)) {
            if (gradeList.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                Long count = 0L;
                for (Grade gradeItem : gradeList) {
                    QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
                    courseSchedulingDetailQueryWrapper.eq("grade_id", gradeItem.getId());
                    courseSchedulingDetailQueryWrapper.eq("lesson_type", 1);
                    courseSchedulingDetailQueryWrapper.eq("status", 0);
                    Long schedulingCount = iCourseSchedulingDetailService.count(courseSchedulingDetailQueryWrapper);
                    if (schedulingCount > 0) {
                        count = count + schedulingCount;
                        stringBuilder.append(gradeItem.getName()).append(",");
                    }
                }
                //允许时间冲突
                if (grade.getAllowTimeClash() != null && !grade.getAllowTimeClash().equals(1)) {
                    if (count > 0) {
                        return new Result(Code.ERROR, "", "该时间段老师已经有排课，" + stringBuilder.toString() + "不能重复排课");
                    }
                }
            }
        }

        gradeQueryWrapper.clear();
        gradeQueryWrapper.ne("id", grade.getId());
        gradeQueryWrapper.eq("school_id", grade.getSchoolId());
        gradeQueryWrapper.eq("year_part", grade.getYearPart());
        gradeQueryWrapper.eq("quarter_num", course.getQuarterNum());
        gradeQueryWrapper.eq("class_room_id", grade.getClassRoomId());
        gradeQueryWrapper.eq("week_dates", grade.getWeekDates());
        gradeQueryWrapper.eq("time_start", grade.getTimeStart().trim());
        gradeQueryWrapper.eq("time_end", grade.getTimeEnd().trim());
        Long count = iGradeService.count(gradeQueryWrapper);
        if (course.getLessonType().equals(1) && grade.getIsAutoScheduling().equals(1)) {
            //允许时间冲突
            if (grade.getAllowTimeClash() != null && !grade.getAllowTimeClash().equals(1)) {
                if (count > 0) {
                    return new Result(Code.ERROR, "", "该时间段教室已经有排课，不能重复排课");
                }
            }
        }
        //班型更改,顺位重置为0


        boolean isUpdateCourseType = false;
        if (!gradeOld.getCourseTypeId().equals(grade.getCourseTypeId())) {
            grade.setPositionNum(0);
            grade.setStartScore(BigDecimal.ZERO);
            grade.setEndScore(BigDecimal.ZERO);
            isUpdateCourseType = true;
        }
        grade.setLessonType(course.getLessonType());
        Integer schedulintCount = iGradeService.updateTo(grade);
        String msg = "";
        // 调整分班学员班型
        iStudentGradeService.updateClassTypeByGradeId(grade.getCourseTypeId(), grade.getId());
        if (isUpdateCourseType) {
            msg = "保存成功,由于班型改变，排班顺位已重置，请到排班顺位重新设置";
            return new Result(Code.OK, "", msg);
        } else {
            msg = "保存成功，成功添加：" + schedulintCount + "次排课，请到日程排课列表里核对，排课是否正确";
            return new Result(Code.OK, "", msg);
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("grade_id", id);
        studentGradeQueryWrapper.ne("status", 3);
        studentGradeQueryWrapper.ne("reading_status", 3);

        Long count = iStudentGradeService.count(studentGradeQueryWrapper);
        if (count > 0) {
            return new Result(Code.ERROR, "", "班级里存在学员，不能删除");
        }

        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        courseSchedulingDetailQueryWrapper.eq("grade_id", id);
        courseSchedulingDetailQueryWrapper.eq("status", 1);
        count = iCourseSchedulingDetailService.count(courseSchedulingDetailQueryWrapper);
        if (count > 0) {
            return new Result(Code.ERROR, "", "班级存在排课信息不能删除");
        }

        courseSchedulingDetailQueryWrapper.clear();

        courseSchedulingDetailQueryWrapper.eq("grade_id", id);
        iCourseSchedulingDetailService.remove(courseSchedulingDetailQueryWrapper);

        QueryWrapper<StudentGrade> studentGradeQueryWrapperDel = new QueryWrapper<>();
        studentGradeQueryWrapperDel.eq("grade_id", id);
        iStudentGradeService.remove(studentGradeQueryWrapperDel);

        boolean rs = iGradeService.removeById(id);
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    /**
     * 获取课程下的班级【报名时使用】
     *
     * @param schoolId
     * @param courseId
     * @return
     */
    @GetMapping("getGradeForSidAndCid/{schoolId}/{courseId}")
    public Result getGradeForSidAndCid(@PathVariable(value = "schoolId") Long schoolId,
                                       @PathVariable(value = "courseId") Long courseId,
                                       @RequestParam(value = "studentId", required = false) Long studentId) {
        Course course = iCourseService.getById(courseId);
        Integer yearPart = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());
        Integer quarterNum = course.getQuarterNum();
        List<Long> gradeIdList = new ArrayList<>();
        if (studentId != null) {
            Company company = iCompanyService.getById(CommonConstant.companyId);
            if (company != null) {
                if (company.getStuIsHierarchy().equals(1)) {
                    Long count = iOrderApplyService.getApplyCountForIsNew(course.getSubjectsId().toString(), studentId.toString());
                    //为0新生
                    if (count.equals(0L)) {
                        GradePositionRequest gradePositionRequest = iStudentClassTypeService.getAutoDivideClassTypeOrScore(yearPart, quarterNum, course.getSubjectsId(), studentId, course.getYearClassId().getKey());
                        if (gradePositionRequest.getIsHasData().equals(1)) {
                            List<Grade> positionGradeList = iGradeService.getPositionGradeList(yearPart, quarterNum, schoolId, course.getSubjectsId(), course.getYearClassId().getKey(), 1, gradePositionRequest.getType(), gradePositionRequest.getScore(), gradePositionRequest.getClassTypeId());
                            if (positionGradeList.size() > 0) {
                                for (Grade grade : positionGradeList) {
                                    gradeIdList.add(grade.getId());
                                }
                            } else {
                                gradeIdList.add(0L);//显示没有
                            }
                        }
                    }
                }
            }
        }
        List<Grade> gradeList = iGradeService.getGradeForCheck(schoolId, courseId, yearPart, course.getQuarterNum(), gradeIdList, studentId);
        return new Result(Code.OK, new PageResult(gradeList, (long) gradeList.size(), 1L));
    }

    /**
     * 学员分班获取的可分班级
     *
     * @return
     */
    @GetMapping("getGradeForShift/{orderDetailId}/{pageNum}/{pageSize}")
    public Result getGradeForShift(@RequestParam Map reMap, @PathVariable(value = "orderDetailId") Long orderDetailId, @PathVariable(value = "pageNum") Integer pageNum, @PathVariable(value = "pageSize") Integer pageSize) {

        OrderDetail orderDetail = iOrderDetailService.getById(orderDetailId);
        if (orderDetail == null) {
            return new Result(Code.ERROR, "", "报读数据不存在");
        }

        Long schoolId = orderDetail.getSchoolId();
        Long studentId = orderDetail.getStudentId();
        Long courseId = orderDetail.getCourseId();

        StudentClassType studentClassType = iStudentClassTypeService.getOneForYearPart(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getSubjectsId(), studentId);
        if (!this.adminId.equals(1568138350324350975L)) {
            if (this.gradeHierarchy.equals(1)) {
                if (orderDetail.getLessonType().equals(1)) {
                    if (studentClassType == null) {
                        return new Result(Code.ERROR, "", "没有对应班型，请先添加分数");
                    }
                }
            }
        }
        String name = (String) reMap.get("name");

        Page<Grade> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(StringUtils.isNotBlank("name"), "name", name);
        queryWrapper.eq("school_id", schoolId);
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("status", 1);
        if (!this.adminId.equals(1568138350324350975L)) {
            if (StringUtils.isNotBlank(name)) {
                if (this.gradeHierarchy.equals(1)) {
                    if (orderDetail.getLessonType().equals(1)) {
                        queryWrapper.in("course_type_id", studentClassType.getClassTypeIdStr());
                    }
                }
            } else {
                if (this.gradeHierarchy.equals(1)) {
                    //queryWrapper.eq("course_type_id", studentClassType.getClassTypeId());
                    if (orderDetail.getLessonType().equals(1)) {
                        queryWrapper.in("course_type_id", studentClassType.getClassTypeIdStr());
                    }
                }
            }
        }

        //queryWrapper.notInSql("id","select grade_id from student_grade where student_id = "+orderDetail.getStudentId()+" and school_id = "+schoolId+" and course_id = "+courseId+" and `status` = 1 and reading_status = 1");

        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("created_at");

        IPage<Grade> iPage = iGradeService.findAll(page, queryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 调班获取班级
     *
     * @param reMap
     * @return
     */
    @GetMapping("getGradeForChange")
    public Result getGradeForChange(@RequestParam Map<String, String> reMap) {

        String outGradeId = reMap.get("outGradeId");
        String studentIdParam = reMap.get("studentId");

        Grade grade = iGradeService.getById(outGradeId);
        Course course = iCourseService.getById(grade.getCourseId());
        if (grade == null) {
            return new Result(Code.ERROR, "", "班级不存在");
        }
        Long schoolId = grade.getSchoolId();
        Long studentId = Long.parseLong(studentIdParam);
        Long courseId = course.getId();
        StudentClassType studentClassType = iStudentClassTypeService.getOneForYearPart(grade.getYearPart(), course.getQuarterNum(), course.getSubjectsId(), studentId);
        if (!this.adminId.equals(1568138350324350975L)) {
            if (this.gradeHierarchy.equals(1)) {
                if (studentClassType == null) {
                    return new Result(Code.ERROR, "", "没有对应班型，请先添加分数");
                }
            }
        }
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("school_id", schoolId);
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("status", 1);
        if (!this.adminId.equals(1568138350324350975L)) {
            if (this.gradeHierarchy.equals(1)) {
                queryWrapper.eq("course_type_id", studentClassType.getClassTypeId());
            }
        }
        //queryWrapper.notInSql("id","select grade_id from student_grade where student_id = "+orderDetail.getStudentId()+" and school_id = "+schoolId+" and course_id = "+courseId+" and `status` = 1 and reading_status = 1");

        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("created_at");

        List<Grade> gradeList = iGradeService.list(queryWrapper);

        return new Result(Code.OK, new PageResult(gradeList, (long) gradeList.size(), 1L));
    }


    /**
     * 获取班级里的学员
     */
    @GetMapping("/getStudentForGradeId/{gradeId}")
    public Result getStudentForGradeId(@RequestParam Map reMap, @PathVariable(value = "gradeId") Long gradeId) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        String name = (String) reMap.get("name");
        String studentList = (String) reMap.get("studentList");
        String status = StringUtils.isEmpty((String) reMap.get("status")) ? "0" : (String) reMap.get("status");// 0全部 1新生 2老生
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        Grade grade = iGradeService.getById(gradeId);

        List<Long> roleIdList = iRoleAdminService.getRoleIdListForAdminId(this.adminId);
        // 判断是否为新老师
        Integer newTeacher = 0;
        Long teacherId = 0L;
        if (!grade.getLessonType().equals(1)) {// 智能课、刷题班
            if (roleIdList != null && roleIdList.size() > 0) {
                for (Long roleId : roleIdList) {
                    if (roleId.equals(1568160855895937096L)) {
                        newTeacher = 1;
                        break;
                    }
                }
                Staff staff = iStaffService.getOneForAdminid(this.adminId);
                teacherId = staff.getId();
            }
        }


        IPage<Student> gradeStudentList = iStudentService.getStudentForGradeId(gradeId, name, pageNum, pageSize, studentList, status, startDate, endDate, newTeacher, teacherId);
        return new Result(Code.OK, new PageResult(gradeStudentList.getRecords(), (long) gradeStudentList.getTotal(), gradeStudentList.getTotal()));
    }

    /**
     * 添加学员弹窗，获取的学员信息
     *
     * @param reMap
     * @param gradeId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getStudentForShift/{gradeId}/{pageNum}/{pageSize}")
    public Result getStudentForShift(@RequestParam Map reMap,
                                     @PathVariable(value = "gradeId") Long gradeId,
                                     @PathVariable(value = "pageNum") Integer pageNum,
                                     @PathVariable(value = "pageSize") Integer pageSize) {

        Grade grade = iGradeService.getById(gradeId);
        Page<SelectStudent> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SelectStudent> queryWrapper = new QueryWrapper<>();

        String readingStatus = (String) reMap.get("readingStatus");
        String name = (String) reMap.get("name");

        //System.out.print("getStudentForShift:"+name);

        //queryWrapper.eq(StringUtils.isNotBlank(readingStatus),"reading_status",readingStatus);
        queryWrapper.like(StringUtils.isNotBlank(name), "student_name", name);

        if (grade.getLessonType().equals(1)) {
            if (!this.permissionCodeList.contains("search:addstudent:all")) {
                if (StringUtils.isNotBlank(name)) {
                    //queryWrapper.apply("FIND_IN_SET({0},class_type_id_str)>0", grade.getCourseTypeId());
                } else {
                    if (this.gradeHierarchy.equals(1)) {
                        //queryWrapper.eq("class_type_id", grade.getCourseTypeId());
                    }
                }
            }
        }
        //queryWrapper.notInSql("student_id","select student_id from student_grade where grade_id= and status=1 and reading_status in(1,4)");
        Map<String, Object> map = new HashMap<>();
        //map.put("isHierarchy",this.gradeHierarchy);
        Integer isHierarchy = 0;
        Company company = iCompanyService.getById(this.companyId);
        //管理员添加不限制分层
        if (!this.adminId.equals(1568138350324350975L)) {
            if (company != null) {
                //寒假班
                if (grade.getQuarterNum().equals(1) && grade.getLessonType().equals(1)) {
                    isHierarchy = company.getGradeHierarchy();
                    if (isHierarchy == 1) {
                        //分层
                        queryWrapper.apply("FIND_IN_SET({0},class_type_id_str)>0", grade.getCourseTypeId());
                    }
                }
            }
        }
        map.put("isHierarchy", isHierarchy);

        iStudentService.getStudentForShift(page, queryWrapper, grade, name, grade.getCourseTypeId());
        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages(), map));
    }


    /**
     * 获取预分班学员
     *
     * @param gradeId
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getAllotStudent")
    public Result getAllotStudent(@RequestParam(name = "gradeId") Long gradeId,
                                  @RequestParam(name = "name") String name,
                                  @RequestParam(name = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                                  @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        Grade grade = iGradeService.getById(gradeId);
        Course course = iCourseService.getById(grade.getCourseId());

        Quarter lastQuarter = iQuarterService.getLastQuarter(grade.getYearPart(), course.getQuarterNum());

        Integer yearClassId = grade.getYearClassId().getKey();
        if (grade.getQuarterNum().equals(3)) {
            //暑假班属于升班，添加的是年级是小一个年级
            yearClassId = yearClassId - 1;
        }

        lessonType = grade.getLessonType();

        Page<SelectStudent> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SelectStudent> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql(StringUtils.isNotBlank(name), "student_id", "select id from student where name like '%" + name + "%'");
        queryWrapper.notInSql("student_id", "select student_id from student_grade where year_part = " + grade.getYearPart().toString() + " and quarter_num = " + course.getQuarterNum() + " and subjects_id= " + course.getSubjectsId() + " and lesson_type=" + lessonType + " and `status` = 1 and deleted = 0 and reading_status in(0,1,4)");
        queryWrapper.ge("residue_course_count", 3);
        if (grade.getLessonType().equals(1)) {
            queryWrapper.eq("year_class_id", yearClassId);
        }

        /*if (grade.getLessonType().equals(1)) {
            if (this.gradeHierarchy.equals(1)) {
                queryWrapper.apply("FIND_IN_SET({0},class_type_id_str)>0", grade.getCourseTypeId());
            }
            if (!this.permissionCodeList.contains("search:addstudent:all")) {
                if (StringUtils.isNotBlank(name)) {
                    //queryWrapper.apply("FIND_IN_SET({0},class_type_id_str)>0", grade.getCourseTypeId());
                } else {
                    if (this.gradeHierarchy.equals(1)) {
                        //queryWrapper.eq("class_type_id", grade.getCourseTypeId());
                    }
                }
            }
        }*/

        Integer year_and_quarter = Integer.parseInt(lastQuarter.getYearPart() + "" + lastQuarter.getNum());
        //queryWrapper.ge("year_and_quarter",year_and_quarter);
        //queryWrapper.notInSql("student_id","select student_id from student_grade where grade_id= and status=1 and reading_status in(1,4)");

        iStudentService.getAllotStudent(page, queryWrapper, grade, year_and_quarter, lastQuarter.getYearPart(), lastQuarter.getNum(), lessonType, grade.getCourseTypeId());
        StringJoiner studentAtGrade = new StringJoiner(",");//从Java 8开始，内置了一个新的StringJoiner类
        if (StringUtils.isNotBlank(name)) {
            if (page.getTotal() == 0L) {
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.inSql(StringUtils.isNotBlank(name), "student_id", "select id from student where name like '%" + name + "%'");
                studentGradeQueryWrapper.eq("year_part", grade.getYearPart());
                studentGradeQueryWrapper.eq("quarter_num", course.getQuarterNum());
                studentGradeQueryWrapper.eq("school_id", grade.getSchoolId());
                studentGradeQueryWrapper.eq("subjects_id", course.getSubjectsId());
                studentGradeQueryWrapper.eq("status", 1);
                studentGradeQueryWrapper.eq("deleted", 0);
                studentGradeQueryWrapper.in("reading_status", 0, 1, 4);
                List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    Grade gradeAt = iGradeService.getById(studentGrade.getGradeId());
                    if (gradeAt != null) {
                        studentAtGrade.add(gradeAt.getName());
                    }
                }
            }
        }
        Map<String, Object> studentAtGradeMap = new HashMap<>();
        studentAtGradeMap.put("studentAtGrade", studentAtGrade.toString());
        Company company = iCompanyService.getById(this.companyId);
        Integer gradeHierarchy = 0;
        //管理员添加不限制分层
        if (!this.adminId.equals(1568138350324350975L)) {
            if (grade.getLessonType().equals(1)) {
                if (company != null) {
                    gradeHierarchy = company.getGradeHierarchy();
                }
            }
        }

        studentAtGradeMap.put("isHierarchy", gradeHierarchy);
        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages(), studentAtGradeMap));
    }


    /**
     * 班级添加学员
     *
     * @return
     */
    @PostMapping("addGradeStudent")
    @RepeatSubmit(expireSeconds = 30)
    public Result addGradeStudent(@RequestBody StudentGrade studentGrade) {
        //System.out.print(studentGrade);
        Grade grade = iGradeService.getById(studentGrade.getGradeId());

        StringBuilder studentIdBd = new StringBuilder();

        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);

        Integer i = 0;
        Integer count = studentGrade.getStudentIdList().length;


        List<String> stringList = new ArrayList<>();
        String clashStr = "";
        for (String studentId : studentGrade.getStudentIdList()) {
            clashStr = "";
            List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(grade.getYearPart(), grade.getQuarterNum(), Long.parseLong(studentId), grade.getId(), nowDateTime.toString());
            if (repairCourseList.size() > 0) {
                Student student = iStudentService.getById(Long.parseLong(studentId));
                for (RepairCourse repairCourse : repairCourseList) {
                    clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                    stringList.add(clashStr);
                }
            }
        }
        if (stringList.size() > 0) {
            StringBuilder studentBuilder = new StringBuilder();
            studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
            return new Result(Code.ERROR, stringList, studentBuilder.toString());
        }
        /*List<ResStudentGradeData> studentGradeDataList = iStudentGradeService.getStudentScheduling(grade.getYearPart(),grade.getQuarterNum(),grade.getWeekDates(),grade.getTimeStart(),grade.getTimeEnd(),studentIdBd.toString(),"");//这里不需要添加类型：,grade.getLessonType().toString()
        i=0;
        count = studentGradeDataList.size();
        StringBuilder studentBuilder = new StringBuilder();
        if (studentGradeDataList.size()>0){
            for (ResStudentGradeData resStudentGradeData:studentGradeDataList){
                studentBuilder.append(resStudentGradeData.getStudentName());
                studentBuilder.append(",");
//                if (i<(count-1)){
//                    studentBuilder.append(",");
//                }
                i++;
            }
            studentBuilder.append("存在时间冲突");
            return new Result(Code.ERROR,studentGradeDataList,studentBuilder.toString());
        }*/

        if (grade.getFullCount() != null && grade.getFullCount() > 0 && (grade.getLessonType() == 2 || grade.getLessonType() == 3)) {
            // 获取原本班级在读学生数量
            Integer studyCount = iStudentGradeService.getGradeStudyCount(studentGrade.getGradeId());
            if (studyCount + count > grade.getFullCount()) {
                return new Result(Code.ERROR, "", "已超出班级人数上限，无法继续添加学员");
            }
        }

        if (this.isSuper != 1) {
            Quarter quarter = iQuarterService.getQuarterForYearAndNum(grade.getYearPart(), grade.getQuarterNum());
            for (String studentId : studentGrade.getStudentIdList()) {
                //学期班
                if (quarter.getType().equals(1)) {
                    //非周末
                    if (!grade.getWeekDates().equals("6") && !grade.getWeekDates().equals("0")) {
                        String planGradeName = iStudentGradeService.getWeekDatesPlanGrade(grade.getYearPart(), grade.getQuarterNum(), Long.valueOf(studentId), grade.getWeekDates());
                        if (StringUtils.isNotBlank(planGradeName)) {
                            return new Result(Code.ERROR, "", CommonUtil.getWeekForId(Integer.parseInt(grade.getWeekDates())) + "已排：" + planGradeName + ",添加失败");
                        }
                    } else {
                        //周末
                        List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(grade.getYearPart(), grade.getQuarterNum(), Long.valueOf(studentId), grade.getId(), nowDateTime.toString());
                        if (repairCourseList.size() > 0) {
                            Student student = iStudentService.getById(studentId);
                            for (RepairCourse repairCourse : repairCourseList) {
                                clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                                stringList.add(clashStr);
                            }
                        }
                        if (stringList.size() > 0) {
                            StringBuilder studentBuilder = new StringBuilder();
                            studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
                            return new Result(Code.ERROR, stringList, studentBuilder.toString());
                        }
                    }
                } else {
                    //假期班
                    List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(grade.getYearPart(), grade.getQuarterNum(), Long.valueOf(studentId), grade.getId(), nowDateTime.toString());
                    if (repairCourseList.size() > 0) {
                        Student student = iStudentService.getById(Long.valueOf(studentId));
                        for (RepairCourse repairCourse : repairCourseList) {
                            clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                            stringList.add(clashStr);
                        }
                    }
                    if (stringList.size() > 0) {
                        StringBuilder studentBuilder = new StringBuilder();
                        studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
                        return new Result(Code.ERROR, stringList, studentBuilder.toString());
                    }
                }
            }
        }

        iGradeService.addStudent(studentGrade.getGradeId() + "", studentGrade.getStudentIdList());
        Course course = iCourseService.getById(grade.getCourseId());
        if (grade.getLessonType().equals(1)) {
            for (String studentId : studentGrade.getStudentIdList()) {
                iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), Long.parseLong(studentId), course.getSubjectsId());

                //智能课、刷题班分班
                StudentGrade studentGradeAllot = new StudentGrade();
                studentGradeAllot.setYearPart(grade.getYearPart());
                studentGradeAllot.setQuarterNum(grade.getQuarterNum());
                studentGradeAllot.setSchoolId(grade.getSchoolId());
                studentGradeAllot.setGradeId(grade.getId());
                studentGradeAllot.setStudentId(Long.parseLong(studentId));
                studentGradeAllot.setSubjectsId(course.getSubjectsId());
                studentGradeAllot.setLessonType(grade.getLessonType());
                iMqPushService.autoAllotStudentGrade(studentGradeAllot);
                try {
                    iMqPushService.updateIsPresort(grade.getSchoolId(), Long.parseLong(studentId), grade.getYearPart(), course.getQuarterNum(), course.getSubjectsId(), course.getLessonType());
                } catch (Exception e) {
                }
            }
        }

        return new Result(Code.OK, "", "");
    }


    /**
     * 预分班级添加学员
     *
     * @return
     */
    @PostMapping("addPresortStudent")
    @RepeatSubmit(expireSeconds = 30)
    public Result addPresortStudent(@RequestBody StudentGrade studentGrade) {
        Grade grade = iGradeService.getById(studentGrade.getGradeId());
        Course course = iCourseService.getById(grade.getCourseId());

        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);

        //System.out.print(studentGrade);
        List<String> stringList = new ArrayList<>();
        String clashStr = "";
        for (String studentId : studentGrade.getStudentIdList()) {
            clashStr = "";
            List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(grade.getYearPart(), grade.getQuarterNum(), Long.parseLong(studentId), grade.getId(), nowDateTime.toString());
            if (repairCourseList.size() > 0) {
                Student student = iStudentService.getById(Long.parseLong(studentId));
                for (RepairCourse repairCourse : repairCourseList) {
                    clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                    stringList.add(clashStr);
                }
            }
        }
        if (stringList.size() > 0) {
            StringBuilder studentBuilder = new StringBuilder();
            studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
            return new Result(Code.ERROR, stringList, studentBuilder.toString());
        }

        //与精品课冲突
        /*String startDateTime =
        String endDateTime
        List<SchedulingClash> schedulingClashList = iCourseSchedulingDetailService.schedulingClash(grade.getYearPart(), grade.getQuarterNum(), grade.getSchoolId(), , grade.getTimeStart(), grade.getTimeEnd(), "1","");

        StringBuilder studentClashBuilder = new StringBuilder();
        for (SchedulingClash schedulingClash:schedulingClashList){
            String schoolTime = schedulingClash.getTimeStart()+"-"+schedulingClash.getTimeEnd();
            String courseTypeName = CommonUtil.getCourseTypeName(schedulingClash.getCourseType());
            studentClashBuilder.append(schedulingClash.getStudentName()).append("与").append(courseTypeName).append(schoolTime);
            if (StringUtils.isNotBlank(schedulingClash.getGradeName())){
                studentClashBuilder.append(",").append(schedulingClash.getGradeName());
            }
            studentClashBuilder.append("存在时间冲突");
            studentClashBuilder.append("；");
        }
        String studentClash = studentClashBuilder.toString();
        if (StringUtils.isNotBlank(studentClash)){
            return new Result(Code.ERROR,"",studentClash);
        }
        */

        iGradeService.presortGrade(studentGrade.getGradeId().toString(), studentGrade.getStudentIdList());
        return new Result(Code.OK);
    }


    /**
     * 结班
     *
     * @param studentGrade
     * @return
     */
    @PutMapping("endOfShift")
    public Result endOfShift(@RequestBody StudentGrade studentGrade) {
        Grade grade = iGradeService.getById(studentGrade.getGradeId());
        if (!grade.getStatus().equals(StatusGradeEnum.NORMAL)) {
            return new Result(Code.ERROR, "", "结班失败,只有状态为“正常”的才能结班");
        }
        boolean rs = iGradeService.endOfShift(studentGrade.getGradeId());
        return new Result(Code.OK);
    }

    @PutMapping("batchEndOfShift")
    @ApiOperation("批量结班")
    public Result batchEndOfShift(@RequestBody Map reMap) {
        List<String> gradeIds = (List<String>) reMap.get("gradeIds");
        QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
        gradeQueryWrapper.ne("status", 1);
        gradeQueryWrapper.in("id", gradeIds);
        Long count = iGradeService.count(gradeQueryWrapper);
        if (count > 0) {
            return new Result(Code.ERROR, "", "结班失败,只有状态为“正常”的才能结班");
        }

        for (String id : gradeIds) {
            iGradeService.endOfShift(Long.parseLong(id));
        }
        return new Result(Code.OK, null, "批量结班成功~");
    }


    /**
     * 班级复课
     *
     * @return
     */
    @PostMapping("/agrainGrade")
    public Result agrainGrade(@RequestBody Grade grade) {
        Grade gradeInfo = iGradeService.getById(grade.getId());
        if (!gradeInfo.getStatus().equals(StatusGradeEnum.STOP)) {
            return new Result(Code.ERROR, "", "复课失败,只有状态为“停课”的才能复课");
        }
        //按班级复课
        iGradeService.agrainGrade(gradeInfo);
        return new Result(Code.OK, null, "复课成功");
    }

    /**
     * 获取插班补课班级
     *
     * @return
     */
    @GetMapping("getRepairGrade")
    public Result getRepairGrade(@RequestParam(value = "schoolId", defaultValue = "") String schoolId,
                                 @RequestParam(value = "courseId", defaultValue = "", required = false) String courseId,
                                 @RequestParam(value = "gradeName", defaultValue = "", required = false) String gradeName,
                                 @RequestParam(value = "lessonType", defaultValue = "", required = false) String lessonType,
                                 @RequestParam(value = "subjectsId", defaultValue = "", required = false) String subjectsId) {

        Quarter quarterInfo = iQuarterService.getNowQuarter();
        List<Grade> gradeList = iGradeService.getRepairGrade(schoolId, courseId, subjectsId, gradeName, lessonType, quarterInfo.getYearPart(), quarterInfo.getNum());
        return new Result(Code.OK, new PageResult(gradeList, (long) gradeList.size(), 1L));
    }

    /**
     * 添加前获取的数据
     *
     * @return
     */
    @GetMapping("/getAddBeforeData/{courseId}")
    public Result getAddBeforeData(@PathVariable(value = "courseId") Long courseId) {
        Course course = iCourseService.findOne(courseId);
        //是否假期
        Integer isVacation = iDictService.getIsVacation(course.getQuarterNum());
        Map<String, Object> map = new HashMap<>();
        map.put("isVacation", isVacation);

        Integer yearPart = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());

        Integer gradeSection = CommonUtil.getGradeSectionForYearClassId(course.getYearClassId().getKey());
        LocalDate openDate = iCourseSchedulingAlwaysService.getStartDate(yearPart, course.getQuarterNum(), gradeSection, null);
        LocalDate endDate = iCourseSchedulingAlwaysService.getEndDate(yearPart, course.getQuarterNum(), gradeSection, null);


        map.put("openDate", openDate);
        map.put("endDate", endDate);

        return new Result(Code.OK, map, "");
    }

    /**
     * 批量删除
     *
     * @param reMap
     * @return
     */
    @PostMapping("/removeStudentForGradeId")
    public Result removeStudentForGradeId(@RequestBody Map reMap) {
        List<String> studentIds = (List<String>) reMap.get("studentIds");
        String gradeId = (String) reMap.get("gradeId");
        for (Object object : studentIds) {
            String jsonObject = JSON.toJSONString(object);
            Student student = JSONObject.parseObject(jsonObject, Student.class);
            iStudentGradeService.remove(new QueryWrapper<StudentGrade>().eq("grade_id", gradeId).eq("student_id", student.getId()));
        }

        return new Result(Code.OK, "", "删除成功");
    }

    /**
     * 班级里批量停课
     *
     * @return
     */
    @PostMapping("/batchStopGrade")
    public Result stopGrade(@RequestBody Map reMap) {
        List<String> studentIds = (List<String>) reMap.get("studentIds");
        String gradeId = (String) reMap.get("gradeId");
        for (Object object : studentIds) {
            String jsonObject = JSON.toJSONString(object);
            Student student = JSONObject.parseObject(jsonObject, Student.class);
            StudentGrade studentGrade = new StudentGrade();
            studentGrade.setGradeId(Long.parseLong(gradeId));
            studentGrade.setStudentId(student.getId());
            iStudentGradeService.stopGrade(studentGrade);

            Grade grade = iGradeService.getById(studentGrade.getGradeId());
            Course course = iCourseService.getById(grade.getCourseId());
            iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), studentGrade.getStudentId(), course.getSubjectsId());

        }

        return new Result(Code.OK, "", "停课成功");
    }

    /**
     * 班级停课
     *
     * @return
     */
    @PostMapping("/stopGradeId")
    public Result stopGradeId(@RequestBody Map reMap) {
        String gradeId = (String) reMap.get("gradeId");
        iStudentGradeService.stopGradeId(gradeId);
        return new Result(Code.OK, "", "停课成功");
    }

    /**
     * 记上课（按学员）批量删除
     *
     * @param reMap
     * @return
     */
    @PostMapping("/removeIds")
    public Result removeStudentId(@RequestBody Map<String, Object> reMap) {
        List<String> idsObj = (List<String>) reMap.get("idsObj");

        List<Map<String, Object>> failedStudents = new ArrayList<>();

        for (String id : idsObj) {
            RecordCourse recordCourseInfo = iRecordCourseService.getById(id);
            if (recordCourseInfo == null) {
                addFailedStudent(failedStudents, id, "数据不存在");
                continue;
            }

            Student student = studentService.getById(recordCourseInfo.getStudentId());
            if (student == null) {
                addFailedStudent(failedStudents, id, "找不到对应的学生");
                continue;
            }

            if (!canDeleteRecord(recordCourseInfo)) {
                addFailedStudent(failedStudents, String.valueOf(student.getId()), getDeleteFailureMessage(recordCourseInfo));
                continue;
            }

            boolean deletionSuccess = iRecordCourseService.deleteForId(Long.parseLong(id));
            if (!deletionSuccess) {
                addFailedStudent(failedStudents, String.valueOf(student.getId()), "删除失败");
                continue;
            }

            try {
                iStudentGradeService.updateIsPresort(
                        recordCourseInfo.getSchoolId(),
                        recordCourseInfo.getStudentId(),
                        recordCourseInfo.getYearPart(),
                        recordCourseInfo.getQuarter(),
                        recordCourseInfo.getSubjectsId(),
                        recordCourseInfo.getLessonType()
                );
            } catch (Exception e) {
                addFailedStudent(failedStudents, String.valueOf(student.getId()), "更新学生信息失败: " + e.getMessage());
            }
        }

        if (failedStudents.isEmpty()) {
            return new Result(Code.OK, "", "所有学生记录删除成功");
        } else {
            List<String> failedStudentNames = failedStudents.stream()
                    .map(map -> (String) map.get("name") + "（" + (String) map.get("message") + "）")
                    .collect(Collectors.toList());
            return new Result(Code.ERROR, failedStudents, "部分学生记录删除失败：" + String.join(",", failedStudentNames));
        }
    }

    private boolean canDeleteRecord(RecordCourse recordCourseInfo) {
        return !(recordCourseInfo.getIsRepair().equals(1) ||
                (recordCourseInfo.getIsRepair().equals(2) && recordCourseInfo.getRepairEndDateTime().isAfter(LocalDateTime.now().truncatedTo(ChronoUnit.MILLIS))) ||
                (recordCourseInfo.getCourseType().equals(3) && recordCourseInfo.getStatus().equals(1)));
    }

    private String getDeleteFailureMessage(RecordCourse recordCourseInfo) {
        if (recordCourseInfo.getIsRepair().equals(1)) {
            return "已补课，不能修改";
        } else if (recordCourseInfo.getIsRepair().equals(2) && recordCourseInfo.getRepairEndDateTime().isAfter(LocalDateTime.now().truncatedTo(ChronoUnit.MILLIS))) {
            return "已安排补课，不能修改";
        } else if (recordCourseInfo.getCourseType().equals(3) && recordCourseInfo.getStatus().equals(1)) {
            return "补课类型数据，不能修改";
        } else {
            return "不能修改";
        }
    }

    private void addFailedStudent(List<Map<String, Object>> failedStudents, String studentId, String message) {
        Student student = studentService.getById(studentId);
        Map<String, Object> failedStudentInfo = new HashMap<>();
        failedStudentInfo.put("name", student.getName());
        failedStudentInfo.put("studentId", studentId);
        failedStudentInfo.put("message", message);
        failedStudents.add(failedStudentInfo);
    }

    /**
     * 批量删除班级
     *
     * @param reMap
     * @return
     */
    @PostMapping("/removeGradeIds")
    public Result removeGradeIds(@RequestBody Map<String, Object> reMap) {
        List<String> gradeIdList = (List<String>) reMap.get("gradeIdList");
        List<Map<String, Object>> failedStudents = new ArrayList<>();

        for (String id : gradeIdList) {
            Map<String, Object> failedStudentInfo = new HashMap<>();
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("grade_id", id);
            studentGradeQueryWrapper.ne("status", 3);
            studentGradeQueryWrapper.ne("reading_status", 3);

            Long count = iStudentGradeService.count(studentGradeQueryWrapper);
            if (count > 0) {
                failedStudentInfo.put("id", id);
                failedStudentInfo.put("name", iGradeService.getById(id).getName());
                failedStudentInfo.put("message", "班级里存在学员，不能删除");
                failedStudents.add(failedStudentInfo);
                continue;
            }

            QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
            courseSchedulingDetailQueryWrapper.eq("grade_id", id);
            courseSchedulingDetailQueryWrapper.eq("status", 1);
            count = iCourseSchedulingDetailService.count(courseSchedulingDetailQueryWrapper);
            if (count > 0) {
                failedStudentInfo.put("id", id);
                failedStudentInfo.put("name", iGradeService.getById(id).getName());
                failedStudentInfo.put("message", "班级存在排课信息，不能删除");
                failedStudents.add(failedStudentInfo);
                continue;
            }

            courseSchedulingDetailQueryWrapper.clear();

            courseSchedulingDetailQueryWrapper.eq("grade_id", id);
            iCourseSchedulingDetailService.remove(courseSchedulingDetailQueryWrapper);

            QueryWrapper<StudentGrade> studentGradeQueryWrapperDel = new QueryWrapper<>();
            studentGradeQueryWrapperDel.eq("grade_id", id);
            iStudentGradeService.remove(studentGradeQueryWrapperDel);

            iGradeService.removeById(Long.parseLong(id));
        }

        if (failedStudents.isEmpty()) {
            return new Result(Code.OK, "", "所有班级删除成功");
        } else {
            List<String> failedStudentNames = failedStudents.stream()
                    .map(map -> {
                        String name = (String) map.get("name");
                        String message = (String) map.get("message");
                        return name + "（" + message + "）";
                    })
                    .collect(Collectors.toList());
            return new Result(Code.ERROR, failedStudents, "部分班级删除失败：" + String.join(",", failedStudentNames));
        }
    }

    @GetMapping("getSchoolTransferGradeTeacher")
    @ApiOperation("转校->教师")
    public Result getSchoolTransferGradeTeacher(@RequestParam Map<String, String> reMap) {
        return getSchoolTransferGradeData(reMap, 2);//1老师，2校区老师，3校长，4校区
    }

    @GetMapping("getSchoolTransferGradeSchool")
    @ApiOperation("转校->校长")
    public Result getSchoolTransferGradeSchool(@RequestParam Map<String, String> reMap) {
        return getSchoolTransferGradeData(reMap, 3);//这个是先左边栏筛选后，右边在显示内容
    }

    private Result getSchoolTransferGradeData(Map<String, String> reMap, int type) {//1老师，2校区老师，3校长，4校区
        String schoolId = reMap.get("schoolIdList") != null && !reMap.get("schoolIdList").isEmpty() ? reMap.get("schoolIdList") : "";
        String classRoomId = reMap.get("classRoomIdList") != null && !reMap.get("classRoomIdList").isEmpty() ? reMap.get("classRoomIdList") : "";
        String courseId = reMap.get("courseIdList") != null && !reMap.get("courseIdList").isEmpty() ? reMap.get("courseIdList") : "";
        String yearPart = reMap.get("yearPart") != null && !reMap.get("yearPart").isEmpty() ? reMap.get("yearPart") : "";
        String quarterNum = reMap.get("quarterNumList") != null && !reMap.get("quarterNumList").isEmpty() ? reMap.get("quarterNumList") : "";
        String lessonType = reMap.get("lessonType") != null && !reMap.get("lessonType").isEmpty() ? reMap.get("lessonType") : "1";
        String teacherName = reMap.get("teacherName") != null && !reMap.get("teacherName").isEmpty() ? reMap.get("teacherName") : null;
        String teacherId = reMap.get("teacherId") != null && !reMap.get("teacherId").isEmpty() ? reMap.get("teacherId") : null;

        String yearClassIdString = reMap.get("yearClassId") != null && !reMap.get("yearClassId").isEmpty() ? reMap.get("yearClassId") : null;
        String[] yearClassId = new String[0];
        if (yearClassIdString != null) {
            yearClassId = yearClassIdString.split(",");
        }

        String subjectsIdString = reMap.get("subjectsId") != null && !reMap.get("subjectsId").isEmpty() ? reMap.get("subjectsId") : null;
        String[] subjectsId = new String[0];
        if (subjectsIdString != null) {
            subjectsId = subjectsIdString.split(",");
        }

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize"));

        Page<Grade> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        String status = reMap.get("status");


        if (StringUtils.isBlank(yearPart)) {
            yearPart = quarterNow.getYearPart().toString();
        }
        if (StringUtils.isBlank(quarterNum)) {
            quarterNum = quarterNow.getNum().toString();
        }

        if (StringUtils.isBlank(schoolId)) {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }

        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        queryWrapper.eq(StringUtils.isNotBlank(classRoomId), "class_room_id", classRoomId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq("status", status);
        }
        if (yearClassId.length > 0) {
            queryWrapper.in("year_class_id", yearClassId);
        }
        if (subjectsId.length > 0) {
            queryWrapper.in("subjects_id", subjectsId);
        }


        queryWrapper.eq("deleted", 0);
        queryWrapper.notInSql("id", "select grade_id from change_school_content WHERE deleted = 0 AND grade_id = grade_view.id");

//1老师，2校区老师，3校长，4校区
//        if (type == 3 && teacherName != null) {
//            queryWrapper.inSql("teacher_id", "select admin_id from role_admin where role_id = 1568160887369994242 AND admin_id IN (select id from staff where id = role_admin.admin_id AND deleted = 0 AND `name` LIKE '%" + teacherName + "%')");
//        } else {
//            if (type == 3) {
//                queryWrapper.inSql("teacher_id", "select admin_id from role_admin where role_id = 1568160887369994242 ");
//            } else
        if (teacherName != null) {
            queryWrapper.inSql("teacher_id", "select id from staff where id = grade_view.teacher_id AND deleted = 0 AND `name` LIKE '%" + teacherName + "%' ");
        } else {
            if (this.sourseLeveEnum.equals(SourseLeveEnum.ONESELF)) {
                queryWrapper.eq("teacher_id", this.adminId);
            }
        }
//        }
        queryWrapper.orderByDesc("created_at");

        IPage<Grade> iPage = iGradeService.findAll(page, queryWrapper);

        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("/gradePosition")
    @ApiOperation("排班顺位")
    public Result gradePosition(@RequestParam Map<String, String> reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? -1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? -1 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<Grade> page = new Page<>(pageNum, pageSize);

        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String schoolId = reMap.get("schoolId");
        String yearClassId = reMap.get("yearClassId");
        String subjectsId = reMap.get("subjectsId");
        String teacherId = reMap.get("teacherId");
        String status = reMap.get("status");//0未满班 1满班
        String gradeId = reMap.get("gradeId");
        String isDescOrAsc = reMap.get("isDescOrAsc");// 0正序 1倒序

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(yearPart), "grade.year_part", yearPart);
        wrapper.eq(StringUtils.isNotBlank(quarterNum), "grade.quarter_num", quarterNum);
        wrapper.inSql(StringUtils.isNotBlank(schoolId), "grade.school_id", schoolId);
        wrapper.eq(StringUtils.isNotBlank(yearClassId), "grade.year_class_id", yearClassId);
        wrapper.eq(StringUtils.isNotBlank(subjectsId), "grade.subjects_id", subjectsId);
        wrapper.eq(StringUtils.isNotBlank(teacherId), "grade.teacher_id", teacherId);
        wrapper.eq(StringUtils.isNotBlank(gradeId), "grade.id", gradeId);
        wrapper.eq("grade.lesson_type", 1);
        wrapper.eq("grade.deleted", 0);
//        if (StringUtils.isBlank(status) || (StringUtils.isNotBlank(status) && !status.equals("2"))) {
//            wrapper.gt("grade.position_num", 0);
//        }

        wrapper.groupBy("grade.id");

        if (StringUtils.isNotBlank(status)) {
            if (status.equals("0")) {
                wrapper.having("grade.full_count > student_count and grade.full_count <> 0");
            } else if (status.equals("1")) {
                wrapper.having("grade.full_count <= student_count and grade.full_count <> 0");
            } else if (status.equals("2")) {
                wrapper.having("grade.full_count = 0");
            }
        }

        if (StringUtils.isNotBlank(isDescOrAsc)) {
            if (isDescOrAsc.equals("0")) {
                wrapper.orderByAsc("position_num");
            } else if (isDescOrAsc.equals("1")) {
                wrapper.orderByDesc("position_num");
            }
        }

        iGradeService.getGradePosition(page, wrapper);

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), Code.GET_OK_MSG);
    }

    @PostMapping("/updateGradeSequence")
    @ApiOperation("添加/修改班级排班顺位设置")
    public Result updateGradeSequence(@RequestBody Grade grade) {
        Grade gradeServiceByInfo = null;
        if (grade.getId() != null) {
            gradeServiceByInfo = iGradeService.getById(grade.getId());
            if (gradeServiceByInfo == null) {
                return new Result(Code.OK, null, "该班级不存在");
            }
        }

        Integer count = iGradeLayerService.getLayerCount(gradeServiceByInfo.getYearPart(), gradeServiceByInfo.getQuarterNum(), gradeServiceByInfo.getSubjectsId(), gradeServiceByInfo.getYearClassId().getKey(), gradeServiceByInfo.getCourseTypeId(), gradeServiceByInfo.getLessonType(), grade.getStartScore(), grade.getEndScore());
        if (count.equals(0)) {
            GradeLayer gradeLayer = iGradeLayerService.getLayer(gradeServiceByInfo.getYearPart(), gradeServiceByInfo.getQuarterNum(), gradeServiceByInfo.getSubjectsId(), gradeServiceByInfo.getYearClassId().getKey(), gradeServiceByInfo.getCourseTypeId(), gradeServiceByInfo.getLessonType());
            String classTypeName = iCourseTypeService.getNameForId(gradeServiceByInfo.getCourseTypeId());
            String reminder = "提示：【" + gradeServiceByInfo.getYearClassId().getValue() + classTypeName + "】";
            if (Objects.nonNull(gradeLayer)) {
                reminder = reminder + "分数段为" + gradeLayer.getStartScore() + "~" + gradeLayer.getEndScore() + "，请调整后重试";
            } else {
                reminder = reminder + "分数段不存在，请先进行分层设置";
            }
            return new Result(Code.ERROR, "", reminder);
        }
        iGradeService.saveOrUpdate(grade);
        return new Result(Code.OK, null, Code.OK_MSG);
    }

    @GetMapping("/floatList")
    @ApiOperation("浮动排班列表")
    public Result floatList(@RequestParam Map<String, String> reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? -1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? -1 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<Grade> page = new Page<>(pageNum, pageSize);

        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String schoolId = reMap.get("schoolId");
        String yearClassId = reMap.get("yearClassId");
        String subjectsId = reMap.get("subjectsId");
        String teacherId = reMap.get("teacherId");
        String gradeId = reMap.get("gradeId");
        String classRoomId = reMap.get("classRoomId");
        String courseTypeId = reMap.get("courseTypeId");
        String isDescOrAsc = reMap.get("isDescOrAsc");// 0正序 1倒序
        String isFieldToSc = reMap.get("isFieldToSc");// 要排序的字段
        String iSeal = reMap.get("isSeal");// 1为封班，0未不封班
        String startDate = reMap.get("startDate");// 开始时间
        String endDate = reMap.get("endDate");// 结束时间

        if (StringUtils.isNotBlank(startDate)) {
            startDate += " 00:00:00";
        }
        if (StringUtils.isNotBlank(endDate)) {
            endDate += " 23:59:59";
        }

        iGradeService.getGradeFloatList(page, yearPart, quarterNum, yearClassId, courseTypeId, subjectsId, schoolId, teacherId, classRoomId, gradeId, isDescOrAsc, isFieldToSc, iSeal, startDate, endDate);

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), Code.GET_OK_MSG);
    }

    @PutMapping("/iSeal")
    @ApiOperation("修改封班状态")
    //@RequiresPermissions(value = "manage:apply")
    public Result patchProduct(@RequestBody Grade gradeParam) {
        Grade grade = iGradeService.getById(gradeParam.getId());
        if (Objects.isNull(grade)) {
            return new Result(Code.EXP_ERROR, Code.EXP_MSG, "该班级不存在");
        }
        grade.setIsSeal(gradeParam.getIsSeal());
        iGradeService.updateById(grade);
        return new Result(Code.UPDATE_OK, null, Code.UPDATE_OK_MSG);
    }

    @GetMapping("/timetable")
    @ApiOperation("班级列表中的课程表")
    public Result timetable(@RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
                            @RequestParam(value = "pageSize", defaultValue = "-1") Integer pageSize,
                            @RequestParam(value = "gradeId", required = false) String gradeId,
//                                     @RequestParam(value = "subjectsId", required = false) String subjectsId,
                            @RequestParam(value = "yearPart", required = false) Integer yearPart,
                            @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
                            @RequestParam(value = "studentName", required = false) String studentName,
                            @RequestParam(value = "isExcel", defaultValue = "0", required = false) Integer isExcel) throws IOException {

        Page<Grade> page = new Page<>(pageNum, pageSize);

        Grade grade = iGradeService.getById(gradeId);

        if (grade == null) {
            return new Result(Code.EXP_ERROR, Code.EXP_MSG, "该班级不存在");
        }

        Integer status = 1;// 根据年份学期判断是否只查询在读学员
        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null || quarterNum == null) {
            yearPart = quarterNow.getYearPart();
            quarterNum = quarterNow.getNum();
        }
        if (quarterNow != null) {
            if (!yearPart.equals(quarterNow.getYearPart()) || !quarterNum.equals(quarterNow.getNum())) {
                status = 0;
            }
        }
        Long subjectsId = grade.getSubjectsId();
        Integer lessonType = grade.getLessonType();

        iGradeService.timetableByGradeId(page, yearPart, quarterNum, gradeId, String.valueOf(subjectsId), status, studentName, lessonType);

        if (isExcel == 1) {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet(grade.getName() + "课程表");
            CellStyle headerCellStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();// 创建字体对象
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 16);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
            headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
            headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            Row headerRow = sheet.createRow(0);
            headerRow.setHeightInPoints(25);
            sheet.createFreezePane(0, 1);// 冻结首行
            headerCellStyle.setFont(headerFont);

            CellStyle cellStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setFontHeightInPoints((short) 13);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setFont(font);

            List<String> headList = new ArrayList<>();
            headList.add("学员姓名");
            headList.add("在读学校");
            if (subjectsId == 1) {
                headList.add("英语精品课");
                headList.add("英语智能课");
            } else if (subjectsId == 2) {
                headList.add("数学精品课");
                headList.add("数学刷题班");
            } else if (subjectsId == 3) {
                headList.add("物理精品课");
                headList.add("物理刷题班");
            }

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }

            int rowIndex = 1;// 数据行起始索引

            for (Grade grade1 : page.getRecords()) {
                Row row = sheet.createRow(rowIndex++);

                Cell cell1 = row.createCell(0);
                cell1.setCellValue(grade1.getStudentName());
                sheet.setColumnWidth(0, 20 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(grade1.getReadingSchoolName());
                sheet.setColumnWidth(1, 50 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(2);
                if (grade1.getTimeStart() != null && grade1.getTimeEnd() != null) {
                    cell3.setCellValue(grade1.getTimeStart() + " - " + grade1.getTimeEnd());
                }
                sheet.setColumnWidth(2, 35 * 256);
                cell3.setCellStyle(cellStyle);

                Cell cell4 = row.createCell(3);
                if (grade1.getSchoolTime() != null && !grade1.getSchoolTime().isEmpty()) {
                    cell4.setCellValue(grade1.getSchoolTime());
                }
                sheet.setColumnWidth(3, 50 * 256);
                cell4.setCellStyle(cellStyle);
            }

            String fileName = "课程表导出" + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/zip");//设置为zip格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();
        }

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), Code.GET_OK_MSG);
    }


}
